package com.lzx.givealike.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzx.givealike.entity.Article;
import com.lzx.givealike.entity.GiveALike;
import com.lzx.givealike.entity.User;
import com.lzx.givealike.mapper.ArticleMapper;
import com.lzx.givealike.mapper.GiveALikeMapper;
import com.lzx.givealike.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/giveALike")
public class GiveALikeController {

    @Resource
    private UserMapper userMapper;

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private GiveALikeMapper giveALikeMapper;

    //登录
    @PostMapping("/login")
    public User login(@RequestBody User user) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", user.getUsername());
        User vo = userMapper.selectOne(userQueryWrapper);
        if (vo != null && Objects.equals(vo.getPassword(), user.getPassword())) {
            return vo;
        } else {
            return null;
        }
    }

    //获取所有文章数据
    //TODO 优化建议：使用分页，减少并发
    @GetMapping("/getList")
    public List<Article> getList() {
        List<Article> articles = articleMapper.selectList(null);
        List<Article> list = new ArrayList<>();
        for (Article item : articles) {
            QueryWrapper<GiveALike> wrapper = new QueryWrapper<>();
            wrapper.eq("article_id", item.getId());
            GiveALike giveALike = giveALikeMapper.selectOne(wrapper);
            if (giveALike == null || giveALike.getIsLike() == 0) {
                item.setIsLike(0);
            } else {
                item.setIsLike(1);
            }
            list.add(item);
        }
        return list;
    }

    //点赞
    @PostMapping("/saveUserLike")
    @Transactional
    public GiveALike saveUserLike(@RequestBody GiveALike giveALike) {
        QueryWrapper<GiveALike> wrapper = new QueryWrapper<>();
        wrapper.eq("article_id", giveALike.getArticleId()).eq("user_id", giveALike.getUserId());
        GiveALike vo = giveALikeMapper.selectOne(wrapper);
        if (vo != null) {
            if (vo.getIsLike() == 0) {
                vo.setIsLike(1);
            } else {
                vo.setIsLike(0);
            }
            giveALikeMapper.updateById(vo);
            return vo;
        } else {
            giveALike.setIsLike(1);
            giveALikeMapper.insert(giveALike);
            return giveALike;
        }
    }
}
